/**
 * 
 */
package com.brother.goallife;

import java.io.Serializable;
import java.util.Date;

import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;

/**
 * @author anhtuan_truong
 *
 */
public class AuditableInterceptor extends EmptyInterceptor{

	/**
	 * 
	 */
	private static final long serialVersionUID = 4831108643625597819L;

	@Override
	public boolean onSave(Object entity, Serializable id, Object[] state,
			String[] propertyNames, Type[] types) {
		if (entity instanceof Auditable) {
			for (int i = 0; i < propertyNames.length; i++) {
				if ("creationDate".equals(propertyNames[i]) || "modifiedDate".equals(propertyNames[i])){
					state[i] = new Date(); 
				}
			}
			return true;
		}
		return false;
	}
	
	@Override
	public boolean onFlushDirty(Object entity, Serializable id,
			Object[] currentState, Object[] previousState,
			String[] propertyNames, Type[] types) {
		if (entity instanceof Auditable) {
			for (int i = 0; i < propertyNames.length; i++) {
				if ("modifiedDate".equals(propertyNames[i])){
					currentState[i] = new Date(); 
				} else if ("version".equals(propertyNames[i])){
					currentState[i] = ((Integer) currentState[i]) + 1 ; 
				}  
			}
			return true;
		}
		return false;
	}

}
